JavaScript provides multiple ways to handle errors, allowing developers to manage exceptions effectively and maintain code stability. Below are common approaches to error handling:
The try-catch
block is used to catch exceptions and handle errors gracefully.
try {
let result = 10 / 0;
console.log(result); // Output: Infinity
throw new Error("Custom Error Message");
} catch (error) {
console.error("Error caught:", error.message);
} finally {
console.log("Execution continues...");
}
Output: Error caught: Custom Error Message Execution continues...
The throw
statement is used to manually throw exceptions.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.error(error.message);
}
Output: Cannot divide by zero
The Error
object provides additional information about errors.
try {
JSON.parse("{ invalid JSON }");
} catch (error) {
console.error("Error Name:", error.name); // SyntaxError
console.error("Error Message:", error.message); // Unexpected token i in JSON
}
Output: Error Name: SyntaxError Error Message: Unexpected token i in JSON
Promises handle asynchronous errors using the .catch
method.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => reject("Data fetch failed"), 1000);
});
fetchData
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Output (after 1 second): Error: Data fetch failed
When using async/await
, errors are caught using a try-catch
block.
async function fetchData() {
try {
let response = await Promise.reject("Data fetch failed");
console.log(response);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();
Output: Error: Data fetch failed
Proper error handling ensures that your application is resilient and provides meaningful feedback during failures. Combining techniques like try-catch
and Promise error handling can significantly enhance code reliability.